package edu.jhu.secondhome.servlet;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.jhu.secondhome.database.accessors.UserAccessor;
import edu.jhu.secondhome.database.beans.User;

public class RegistrationServlet extends HttpServlet
{
  /**
   * 
   */
  private static final long serialVersionUID = -4509246717148467968L;

  public void init() throws ServletException
  {
  }

  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException
  {
    processRequest(req, resp);
  }

  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException
  {
    processRequest(req, resp);
  }

  public void processRequest(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException
  {
    response.setContentType("text/html;charset=UTF-8");
    ServletContext servletContext = getServletContext();
    
    String email = request.getParameter( "reg_email" );
    String email2 = request.getParameter( "reg_email2" );
    String pass = request.getParameter( "reg_password" );
    String pass2 = request.getParameter( "reg_password2" );
    String firstName = request.getParameter( "reg_firstName" );
    String lastName = request.getParameter( "reg_lastName" );
    String phoneNum = request.getParameter( "reg_phoneNumber" );
    String address1 = request.getParameter( "reg_address1" );
    String address2 = request.getParameter( "reg_address2" );
    String address3 = request.getParameter( "reg_address3" );
    String city = request.getParameter( "reg_city" );
    String state = request.getParameter( "reg_state" );
    String zip = request.getParameter( "reg_zip" );

    ArrayList<String> errors = new ArrayList<String>();
    request.setAttribute("errors", errors);
    
    if ( email.equals("") )
      errors.add( "E-mail is a required field." );
    if ( email2.equals("") )
      errors.add( "You must repeat your e-mail." );
    if ( pass.equals("") )
      errors.add( "Password is a required field." );
    if ( pass2.equals("") )
      errors.add( "You must repeat your password." );
    if ( firstName.equals("") )
      errors.add( "First Name is a required field." );
    if ( lastName.equals("") )
      errors.add( "Last Name is a required field." );
    if ( phoneNum.equals("") )
      errors.add( "Phone number is a required field." );
    // address2 and address3 are optional
    if ( address1.equals("") )
      errors.add( "Address is a required field." );
    if ( city.equals("") )
      errors.add( "City is a required field." );
    if ( state.equals("") )
      errors.add( "State is a required field." );
    if ( zip.equals("") )
      errors.add( "Zip Code is a required field." );

    // return with the basic form errors
    if ( errors.size() > 0 )
    {
      RequestDispatcher dispatcher = servletContext.getRequestDispatcher("/register.jsp");
      dispatcher.forward(request, response);
      return;
    }
    
    if ( !email.equals( email2 ) )
      errors.add( "Your e-mail values must match." );
    if ( !pass.equals( pass2 ) )
       errors.add( "Your password values must match." );
     
    // return with the mismatched email/password errors
    if ( errors.size() > 0 )
    {
      RequestDispatcher dispatcher = servletContext.getRequestDispatcher("/register.jsp");
      dispatcher.forward(request, response);
      return;
    }
    
    try
    {
      UserAccessor userDb = new UserAccessor();

      // Return error if user exists
      if ( userDb.getUserByEmail( email ) != null )
      {
        errors.add( "There is already a user registered to that e-mail address." );
        RequestDispatcher dispatcher = servletContext.getRequestDispatcher("/register.jsp");
        dispatcher.forward(request, response);
        return;
      }
      
      byte[] encryptedPass = User.encryptString( pass );
      String encryptedPassStr = new String( encryptedPass, "UTF-8" );

      String fullAddress = User.createAddressString( address1, address2, address3, city, state, zip );
      
      User newUser = new User(email, encryptedPassStr, firstName, lastName,
          phoneNum, fullAddress, null, null, null, null, null, false );
      userDb.insertUser( newUser );
      
    } catch (SQLException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
      errors.add(e.getMessage());
    } catch (NoSuchAlgorithmException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
      errors.add(e.getMessage());
    }
    
    if ( errors.size() > 0 )
    {
      RequestDispatcher dispatcher = servletContext.getRequestDispatcher("/register.jsp");
      dispatcher.forward(request, response);
      return;
    }
    else
    {
      request.setAttribute("message", "Registration successful!  Welcome, " + firstName );
      RequestDispatcher dispatcher = servletContext.getRequestDispatcher("/index.jsp");
      dispatcher.forward(request, response);
      return;
    }
  }
}
